package com.springStudy.context;


import com.springStudy.service.PetStoreServiceImpl;
import org.junit.Test;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

public class GenericApplicationContextDemo {

    /**
     * 使用ClassPathXmlApplicationContext 初始化容器
     */
    @Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
        printfBeanDefine(context);
        PetStoreServiceImpl petStore = (PetStoreServiceImpl) context.getBean("petStore");
        petStore.printHello();
        PetStoreServiceImpl petStore4systemA = (PetStoreServiceImpl) context.getBean("petStore4systemA");
        petStore4systemA.printHello();

    }

    /**
     * 比较灵活的变体是 GenericApplicationContext 容器加上 BeanDefinitionReader 运行容器。
     */
    @Test
    public void test02(){
        GenericApplicationContext context = new GenericApplicationContext();
        new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");

//        new AnnotatedBeanDefinitionReader(context).
        context.refresh();
        printfBeanDefine(context);

    }

    /**
     * 通过构造方法注入循环依赖问题
     */
    @Test
    public void test03(){
        ApplicationContext context = new ClassPathXmlApplicationContext("cycleServices.xml");
        printfBeanDefine(context);


    }



    private void printfBeanDefine(ApplicationContext context){
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (int i = 0; i < beanDefinitionNames.length; i++) {
            String beanDefinitionName = beanDefinitionNames[i];
            System.out.println(beanDefinitionName);
        }
    }
}
